<?php
namespace app\admin\model;

/*客服模型*/
use app\admin\model\CommonModel;
use app\admin\model\User;

class Kf extends CommonModel
{
    private $table_name = 'kf';
    public function __construct()
    {
       parent::__construct();
    }
    /**初始化参数
     * @param $args [client_id,token,enc_string,nickname]
     * @return array
     */
    private function default_param($args)
    {
        $default = [
            "client_id"     => "",
            "enc_client_id" => "",
            "nickname"      => "匿名",
            "kf_username"  => "",
            "kf_password"   => "",
        ];
        return array_merge($default,$args);
    }

    /**新增一个客服
     * @param $args [kf_username,kf_password,nickname,cate_id]
     * @return client_id
     */
    public function addKf($args)
    {
        //初始化参数
        $args = $this->default_param($args);
        $enc_string= randString(15);
        //客服账号密码不得空
        if(empty($args['kf_username'])  || empty($args['kf_password']) || empty($args['nickname']))
        {
            return $this->returnState(1,"信息填写不完整");
        }
        //如果客服已存在，则返回false
        if(!empty($this->info(['kf_username'=>$args['kf_username']]))){
            return $this->returnState(1,"该用户名已存在，请更换");
        }
        //如果分类不存在，则返回false
        if(!isset($args['cate_id']) || !$this->exist_kfCate($args['cate_id']))
        {
            return $this->returnState(1,"不存在客服职责");
        }
        //插入数据库
        $kf_id =  db($this->table_name)->insertGetId([
            'cate_id'       => $args['cate_id'],
            'nickname'      => $args['nickname'],
            'kf_username'   => $args['kf_username'],
            'kf_password'   => $this->generateKfPassword(['kf_enc_string'=>$enc_string,'kf_password'=>$args['kf_password']]),
            'kf_enc_string' => $enc_string
        ]);

        //插入用户表
        $this->addKfInUser(['kf_id'=>$kf_id]);

        //返回成功标识
        return $this->returnState(0,"成功添加客服");
    }

    /**把客服id插入用户表中
     * @param $args ['kf_id'] kf_id值
     * @return client_id
     */
    public function addKfInUser($args)
    {
        $userModel = new User();
        return $userModel->add_user(['kf_id'=>$args['kf_id']]);
    }

    /**更新客服的匿名称到用户表
     * @param $args
     */
    public function updateNicknameInUser($args)
    {
        db('user')->where(['kf_id'=>$args['kf_id']])->update(['nickname'=>$args['nickname']]);
    }

    /**生成客服密码窜
     * @param $args [kf_password,kf_enc_string]
     * @return string
     */
    private function generateKfPassword($args)
    {
        return md5($args['kf_password'].$args['kf_enc_string']);
    }

    //获取所有客服
    public function all($args = [])
    {
        /**
         * $args参数说明
         * args.cate_id 根据客服的分类id查询
         * args.keyword 根据客服的kf_username,nickname模糊查询
         * pageLimit 每页显示多少条数据 默认15条
         */

        $pageLimit = isset($args['pageLimit']) && intval($args['pageLimit']) > 0 ? $args['pageLimit'] : 15;
        $where = [];
        if(isset($args['cate_id']) && intval($args['cate_id']) > 0)
        {
            $where['c.id'] = intval($args['cate_id']);
        }

        if(isset($args['keyword']) && $args['keyword'])
        {
            $where['k.nickname|k.kf_username'] = ['like','%'.$args['keyword'].'%'];
        }
        //获取数据
        $data = null;
        if(!empty($where))
        {
            $data = db($this->table_name)->field('k.*,c.name cate_name')->alias('k')->join('ecs_kf_cate c','c.id = k.cate_id','LEFT')->where($where)->order('k.kf_id DESC')->paginate($pageLimit);
        }
        else
        {
            $data = db($this->table_name)->field('k.*,c.name cate_name')->alias('k')->join('ecs_kf_cate c','c.id = k.cate_id','LEFT')->order('k.kf_id DESC')->paginate($pageLimit);
        }

        return [
            'data' => $data,
            'page' => $data->render()
        ];
    }

    /**获取一个客服
     * @param array $args key:[kf_id,client_id,kf_username,enc_client_id], 中括号表示任选一个可以查询
     * @return bool
     */
    public function info($args)
    {

        if(empty($args)) return false;
        //参数合并
        $args = $this->default_param($args);
        //如果没有查询信息，返回空
        if((!isset($args['kf_id']) || empty($args['kf_id'] ))
            && empty($args['client_id'] )
            && empty($args['kf_username'])
            && empty($args['enc_client_id'])
        ) return false;

        //根据kf_id,client_id,kf_username,enc_client_id其中一个查询查
        if(!empty($args['kf_id']))
        {
            $filter = ['k.kf_id'=>$args['kf_id']];
        }
        elseif(!empty($args['client_id']))
        {
            $filter = ['u.client_id'=>$args['client_id']];
        }
        elseif(!empty($args['kf_username']))
        {
            $filter = ['k.kf_username'=>$args['kf_username']];
        }
        elseif(!empty($args['enc_client_id']))
        {
            $filter = ['u.enc_client_id'=>$args['enc_client_id']];
        }
        if(empty($filter)) return false;

        //返回查询信息
        return  db($this->table_name)->alias('k')->field('k.*,u.client_secrect,u.enc_string,u.enc_client_id,u.client_id')->join('ecs_user u','u.kf_id = k.kf_id','LEFT')->where($filter)->find();
    }

    //删除客服
    public function del($args)
    {
        /**
         * args参数说明
         * args为一个数组，包含所有的kf_id值
         */
        if(empty($args))
        {
            return $this->returnState(1,"没有客服被删除");
        }
        $this->delKfChat($args);
        db($this->table_name)->where(['kf_id'=>['in',implode(',',$args)]])->delete();
        return $this->returnState(0,"删除完毕");
    }

    //删除客服的所有聊天记录
    public function delKfChat($args)
    {
        /**
         * args参数说明
         * args为一个数组，包含所有的kf_id值
         */

        //查询客服对应的客户端id
        $enc_client_id_arr = db('user')->field('enc_client_id')->where(['kf_id'=>['in',implode(',',$args)]])->select();
        if(!empty($enc_client_id_arr))
        {
            $enc_client_id_total = [];
            foreach($enc_client_id_arr as $k=>$v)
            {
                $enc_client_id_total[] = $v['enc_client_id'];
            }
            //根据客户端id查询聊天信息id
            $data = db('chat_msg_user')->field('msg_id')->where(['fuser|tuser'=>['in',implode(',',$enc_client_id_total)]])->select();
            $msg_id_arr = [];
            if(!empty($data))
            {
                foreach($data as $k=>$v)
                {
                    $msg_id_arr[] = $v['msg_id'];
                }
            }

            //删除消息表
            if(!empty($msg_id_arr))
            {
                db('chat_msg')->where(['id'=>['in',implode(',',$msg_id_arr)]])->delete();
            }
            //删除记录表
            db('chat_msg_user')->where(['fuser|tuser'=>['in',implode(',',$enc_client_id_total)]])->delete();
        }

        //删除用户表
        db('user')->field('enc_client_id')->where(['kf_id'=>['in',implode(',',$args)]])->delete();


    }

    //编辑一个客服
    public function edit($args)
    {
        /**
         * args参数说明
         * args.kf_id
         * args.kf_username
         * args.kf_password
         * args.nickname
         * args.cate_id
         */

        //检查参数
        $args = $this->default_param($args);
        if(!isset($args['kf_id']) || intval($args['kf_id']) == 0)
        {
            return $this->returnState(1,"没有选中客服进行编辑");
        }

        //检查客服身份
        $info = $this->info(['kf_id'=>intval($args['kf_id'])]);
        if(!$info || empty($info))
        {
            return $this->returnState(1,"客服不存在，或者已被删除");
        }

        //如果分类不存在，则返回false
        if(isset($args['cate_id']) && !empty($args['cate_id']))
        {
            if(!$this->exist_kfCate($args['cate_id'])) return $this->returnState(1,"客服职责不存在");
        }

        unset($args['kf_enc_string']);
        //设置了密码
        if(!empty($args['kf_password']))
        {
            $args['kf_enc_string']= $enc_string= randString(15);
            $args['kf_password'] = $this->generateKfPassword(['kf_enc_string'=>$enc_string,'kf_password'=>$args['kf_password']]);
        }

        $id = $info['kf_id'];

        //合并两个数组
        $fields = ['kf_password','kf_username','nickname','kf_enc_string','cate_id'];
        $update = array_merge(resetArr($info,$fields),resetArr($args,$fields));
        $cate_id = $update['cate_id'];
        //删除空的项
        $update = array_filter($update);
        $update['cate_id'] = $cate_id;
        //客服更新
        db($this->table_name)->where(['kf_id'=>$id])->update($update);
        //用户表更新匿名
        if(isset($update['nickname']))
        {
            $this->updateNicknameInUser(['kf_id'=>$id,'nickname'=>$update['nickname']]);
        }
        return $this->returnState(0,"客服信息更新完毕");
    }

    //查询是否存在客服职责
    public function exist_kfCate($id)
    {
        $KfCateModel = new KfCate();
        $data = $KfCateModel->info(['id'=>$id]);
        return $data['error'] == 0 && !empty($data['data']);
    }

    /**客服管理员登录接口
     * @param $args [kf_username,kf_password]
     * @return bool
     */
    public function login($args)
    {
        //初始化参数
        $args = $this->default_param($args);

        if(empty($args['kf_username']) || empty($args['kf_password'])) return false;

        //查询客服信息
        $kf = $this->info(['kf_username'=>$args['kf_username']]);
        //检测密码
        if(empty($kf)
            ||   $kf['is_admin'] != 1
            || !$this->chkKfPassword(['db_password'=>$kf['kf_password'],'kf_password'=>$args['kf_password'],'kf_enc_string'=>$kf['kf_enc_string']])
        ) return false;

        //更新客服加密窜
        $kf['kf_password'] = $args['kf_password'];
        $this->updateKfEncString($kf);

        //更新token
        $userModel = new User();
        $token = $userModel->resetEncString($kf);

        return [
            'kf_id' => $kf['kf_id'],
            'enc_client_id'=> $this->EncUserid($kf['client_id']),
            'username' => $kf['kf_username'],
            'nickname'  => $kf['nickname'],
            'is_kf'     => 1,
            'token'     => $token
        ];

    }

    /**检测kf密码正确性
     * @param $args [db_password数据库字符串,kf_password用户输入的密码,kf_enc_string数据库加密字符串]
     * @return bool
     */
    public function chkKfPassword($args)
    {
        return $args['db_password'] == $this->generateKfPassword($args);
    }

    /**更新客服密码加密窜
     * @param $args [client_id,kf_password]
     */
    private function updateKfEncString($args)
    {
        $enc_string = randString(15);
        db($this->table_name)->where(['kf_id'=>$args['kf_id']])->update([
            'kf_enc_string'=>$enc_string,
            'kf_password'=>$this->generateKfPassword(['kf_password'=>$args['kf_password'],'kf_enc_string'=>$enc_string])
        ]);
    }

    //设置管理员
    public function setAdmin($id)
    {
        db($this->table_name)->where(['kf_id'=>$id])->update(['is_admin'=>1]);
        return $this->returnState(0);
    }

    //取消管理员
    public function cancleAdmin($id)
    {
        db($this->table_name)->where(['kf_id'=>$id])->update(['is_admin'=>0]);
        return $this->returnState(0);
    }
}
